package com.cwj.mansysback.servlet.impl;

import com.cwj.mansysback.service.api.RankService;
import com.cwj.mansysback.service.impl.RankServiceImpl;
import com.cwj.mansysback.servlet.util.MyUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class UpdateRanksServlet extends HttpServlet {

    private static final String UPDATE = "/Lock/Update/Rank";
    private static final String ADD = "/Lock/Add/Rank";
    private static final String DELETE = "/Lock/Delete/Rank";


    RankService rankSer = new RankServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String rid = req.getParameter("rid");

//        String rname = req.getParameter("rname");

        if (rid == null) {
            MyUtils.writeResponse(resp, new Statement(8));
            return;
        }

        Statement statement = new Statement(8);

        boolean isUpdate = req.getRequestURI().contains(UpdateRanksServlet.UPDATE);
        boolean isInsert = req.getRequestURI().contains(UpdateRanksServlet.ADD);
        boolean isDelete = req.getRequestURI().contains(UpdateRanksServlet.DELETE);;

        if ( isUpdate || isInsert) {
            String rname = req.getParameter("rname");
            String rpiece = req.getParameter("rpiece");
            if (rname != null && rpiece != null) {
                if(isUpdate) {
                    if (rankSer.updateRank(rid, rname, Double.parseDouble(rpiece))) {
                        statement.setStatue(0);
                    }
                }else{
                    if (rankSer.insertRank(rid, rname, Double.parseDouble(rpiece))) {
                        statement.setStatue(0);
                    }
                }
            }
        }else if(isDelete){
            if(rankSer.deleteRank(rid)){
                statement.setStatue(0);
            }else{
                statement.setStatue(10);
            }
        }

        MyUtils.writeResponse(resp, statement);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }
}
